<template>
    <div class="jcdManagement">
      <div class="t_fm">
        <el-upload
          class="upload-demo"
          :before-upload="handleZyzc"
          :show-file-list="false"
          multiple
          action=""
        >
          <el-button type="primary">资源资产文件上传.zip</el-button>
        </el-upload>
        <el-upload
          class="upload-demo"
          :before-upload="handleWydc"
          :show-file-list="false"
          multiple
          action=""
        >
          <el-button type="primary">外业调查文件上传.zip</el-button>
        </el-upload>
        <el-button type="warning" @click="handDataValidation">数据验证</el-button>
        <!-- <el-button type="success" @click="handDownload" v-show="visible">下载验证结果</el-button> -->
      </div>
  
      <!-- Tab 页始终显示 -->
      <el-tabs v-model="activeTab">
      <!-- Tab 1: 资源资产文件数据 -->
      <el-tab-pane label="资源资产文件数据" name="zyzcDataTab">
          <el-table :data="zyzcPaginatedData" border style="width: 100%">
            <el-table-column prop="YDBH" label="样地编号"> </el-table-column>
            <el-table-column prop="XZQMC" label="行政区名称"> </el-table-column>
            <el-table-column prop="GTDCTBBSM" label="图斑标识码" min-width="160"> </el-table-column>
            <el-table-column prop="GTDCDLMC" label="地类名称"> </el-table-column>
            <el-table-column prop="ZTBMJ" label="子图斑面积"> </el-table-column>
            <el-table-column prop="ZBGD" label="植被盖度"> </el-table-column>
            <el-table-column prop="PJG" label="平均高"> </el-table-column>
          </el-table>
          <div class="bottom">
            <el-pagination
              :current-page="zyzcCurrentPage"
              background
              layout="total, prev, pager, next, jumper"
              :total="zyzcTotalItems"
              :page-size="pageSize"
              hide-on-single-page
              @current-change="handleZyzcPageChange"
            />
          </div>
        </el-tab-pane>
  
        <!-- Tab 2: 外业调查文件数据 -->
        <el-tab-pane label="外业调查文件数据" name="wydcDataTab">
          <el-table :data="wydcPaginatedData" border style="width: 100%">
            <el-table-column prop="YDBH" label="样地编号"> </el-table-column>
            <el-table-column prop="XZQMC" label="行政区名称"> </el-table-column>
            <el-table-column prop="GTDCTBBSM" label="图斑标识码" min-width="160"> </el-table-column>
            <el-table-column prop="GTDCDLMC" label="地类名称"> </el-table-column>
            <el-table-column prop="ZTBMJ" label="子图斑面积"> </el-table-column>
            <el-table-column prop="ZBGD" label="植被盖度"> </el-table-column>
            <el-table-column prop="PJG" label="平均高"> </el-table-column>
          </el-table>
          <div class="bottom">
            <el-pagination
              :current-page="wydcCurrentPage"
              background
              layout="total, prev, pager, next, jumper"
              :total="wydcTotalItems"
              :page-size="pageSize"
              hide-on-single-page
              @current-change="handleWydcPageChange"
            />
          </div>
        </el-tab-pane>
  
        <!-- Tab 2: 数据验证结果 -->
        <el-tab-pane label="数据验证结果" name="validationResults">
          <!-- <h3>草原外业调查验证结果</h3>
          <el-table
            :data="wydcVerificationResult.map((item) => ({ content: item }))"
            border
          >
            <el-table-column prop="content" label="验证结果" />
          </el-table> -->
          <h3>草原外业调查验证结果</h3>
          <el-table :data="wydcVerificationResult" border>
            <el-table-column prop="GTDCTBBSM" label="图斑标识码" />
            <el-table-column prop="YDBH" label="样地编号" />
            <el-table-column prop="DCRQ" label="调查日期" />
            <el-table-column prop="bz" label="备注" />
            
  
          </el-table>
  
          <h3>草原资源资产验证结果</h3>
          <el-table
            :data="zyzcVerificationResult.map((item) => ({ content: item }))"
            border
          >
            <el-table-column prop="content" label="验证结果" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </template>
  <script>
  import { mapState, mapActions } from "vuex";
  import shp from "shpjs";
  import { isDigit, isDate } from "@/utils/verify.js";
  import { validationRules } from "@/utils/validationRules.js";
  export default {
    name: "jcdManagement",
    data() {
      return {
        form: {},
        tableData: [],
        // paginatedData: [], // 当前页的数据
        // currentPage: 1, // 当前页码
        // pageSize: 10, // 每页显示的数据量
        // totalItems: 0, // 总项目数
        // zyzcData: [],
        wydcVerificationResult: [],
        zyzcVerificationResult: [],
        visible: false,
  
      
     
        // pageSize: 10, // 每页显示的数据量
        activeTab: "zyzcDataTab", // 控制tab切换的变量
        zyzcData: [], // 资源资产数据
        wydcData: [], // 外业调查数据
        pageSize: 10, // 每页显示的数据量
  
        // 资源资产分页
        zyzcCurrentPage: 1,
        zyzcTotalItems: 0,
        zyzcPaginatedData: [],
  
        // 外业调查分页
        wydcCurrentPage: 1,
        wydcTotalItems: 0,
        wydcPaginatedData: [],
      };
    },
    computed: {
      ...mapState({
        myData: "myData",
      }),
    },
    methods: {
      ...mapActions({
        updateData: "updateMyData",
      }),
      handleadd() {
        console.log(this.form);
        this.$router.replace(this.$route.path + "/data");
      },
      handleEdit(row) {
        this.$router.replace({ name: "shapeData", params: row });
      },
      handleDelete(index, rows) {
        this.$confirm("此操作将删除该条数据, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          rows.splice(index, 1);
          this.totalItems = this.tableData.length;
          this.paginateData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      },
      handleVerify(row) {
        console.log(row);
      },
      handleWydc(file, fileList) {
        console.log("-------------", file, fileList);
        const uploadedFile = file;
        const reader = new FileReader();
        reader.onload = (event) => {
          console.log(event);
          shp(event.target.result)
            .then((geojson) => {
              console.log(geojson);
              // this.form = geojson.features[1].properties;
              let array = [];
              geojson.features.forEach((element) => {
                let obj = element.properties;
                array.push(obj);
              });
              this.updateData(array);
              this.tableData = array;
              this.totalItems = this.tableData.length;
              this.paginateData();
            })
            .catch((error) => {
              console.log(error);
            });
        };
        reader.readAsArrayBuffer(uploadedFile);
      },
      // 分页
      paginateData() {
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        this.paginatedData = this.tableData.slice(start, end);
      },
      handleCurrentChange(val) {
        // 当用户切换分页时触发
        this.currentPage = val;
        this.paginateData();
      },
      handleZyzc(file, fileList) {
        console.log("-------------", file, fileList);
        const uploadedFile = file;
        const reader = new FileReader();
        reader.onload = (event) => {
          console.log(event);
          shp(event.target.result)
            .then((geojson) => {
              console.log(geojson);
              // this.form = geojson.features[1].properties;
              let array = [];
              geojson.features.forEach((element) => {
                let obj = element.properties;
                array.push(obj);
              });
              this.zyzcData = array;
            })
            .catch((error) => {
              console.log(error);
            });
        };
        reader.readAsArrayBuffer(uploadedFile);
      },
      handDataValidation() {
        if (this.tableData.length == 0) {
          this.$message.warning("请上传草原外业调查数据！");
          return;
        }
        if (this.zyzcData.length == 0) {
          this.$message.warning("请上传草原资源资产数据！");
          return;
        }
      //   let wydcArray = ["草原外业调查"];
        let wydcArray = [];
        let zyzcArray = ["草原资源资产"];
        this.tableData.forEach((element) => {
          let wydcObj = {
            GTDCTBBSM: element.GTDCTBBSM || "无",
            YDBH: element.YDBH || "无",
            DCRQ: element.DCRQ || "无",
          };
          if (element.YDBH) {
            // 验证外业调查有样地编号数据---
          //   wydcArray.push(`样地编号：${element.YDBH}`);
          //   wydcArray.push(`图斑标识码：${element.GTDCTBBSM}`);
          wydcArray.push(wydcObj);
  
          //   // 动态应用验证规则
          //   for (const field in validationRules) {
          //     const validation = validationRules[field].validate(element[field]);
          //     if (validation) {
          //       wydcArray.push(`-${validation}`);
          //     }
          //   }
         // 动态应用验证规则
         for (const field in validationRules) {
              const validation = validationRules[field].validate(element[field]);
              if (validation) {
                wydcObj.validation = `-${validation}`;
              }
            }
  
            // 验证资源资产数据------------
            for (let i = 0; i < this.zyzcData.length; i++) {
              const element2 = this.zyzcData[i];
              if (element.GTDCTBBSM === element2.GTDCTBBSM) {
                zyzcArray.push(`图斑标识码：${element2.GTDCTBBSM}`);
                if (element.ZBGD !== element2.ZBGD) {
                  zyzcArray.push(
                    `-植被盖度(${element2.ZBGD})与调查值(${element.ZBGD})不相符；`
                  );
                }
                if (element.GTDCDLMC !== element2.GTDCDLMC) {
                  zyzcArray.push(
                    `-地类名称(${element2.GTDCDLMC})与调查值(${element.GTDCDLMC})不相符；`
                  );
                }
                if (element.GTDCDLMC !== element2.GTDCTBMJ) {
                  zyzcArray.push(
                    `-国土调查图斑面积(${element2.GTDCTBMJ})与调查值(${element.GTDCTBMJ})不相符；`
                  );
                }
                if (element.GTDCDLMC !== element2.ZTBMJ) {
                  zyzcArray.push(
                    `-子图斑面积(${element2.ZTBMJ})与调查值(${element.ZTBMJ})不相符；`
                  );
                }
                if (element.GTDCDLMC !== element2.THMJ) {
                  zyzcArray.push(
                    `-退化面积(${element2.THMJ})与调查值(${element.THMJ})不相符；`
                  );
                }
                if (element.GTDCDLMC !== element2.YFMJ) {
                  zyzcArray.push(
                    `-样方面积(${element2.YFMJ})与调查值(${element.YFMJ})不相符；`
                  );
                }
                if (element.GTDCDLMC !== element2.ZRBHDHXQMJ) {
                  zyzcArray.push(
                    `-平均高(${element2.ZRBHDHXQMJ})与调查值(${element.ZRBHDHXQMJ})不相符；`
                  );
                }
              }
            }
            zyzcArray.push("");
            // =========================
          } else {
            // 验证外业调查没有样地编号数据
          //   wydcArray.push(`样地编号：无`);
          //   wydcArray.push(`图斑标识码：${element.GTDCTBBSM}`);
          //   if (isDate(element.DCRQ)) {
          //     wydcArray.push(`-调查日期未填写；`);
          //   }
          //   if (element.bz === "") {
          //     wydcArray.push(`-备注未填写；`);
          //   }
             // 验证外业调查没有样地编号数据
             wydcArray.push(wydcObj);
            if (!isDate(element.DCRQ)) {
              wydcObj.DCRQ = "调查日期未填写";
            }
            if (!element.bz) {
              wydcObj.bz = "备注未填写";
            }
          }
          // wydcArray.push("");
        });
      //   wydcArray.push("\n\n");
        this.wydcVerificationResult = wydcArray;
        this.zyzcVerificationResult = zyzcArray;
        this.$nextTick(() => {
          this.visible = true;
          this.$notify({
            // title: '成功',
            message: "验证完成",
            type: "success",
          });
        });
      },
      downloadTextFile(text, filename) {
        // 创建一个Blob实例，类型为纯文本
        const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
        // 创建一个指向Blob的URL
        const url = URL.createObjectURL(blob);
        // 创建一个a标签
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", filename);
        document.body.appendChild(link);
        // 触发下载
        link.click();
        // 清理
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      },
      // handDownload() {
      //     let wydctext = this.wydcVerificationResult.join('\n');
      //     let zyzctext = this.zyzcVerificationResult.join('\n');
      //     this.downloadTextFile(wydctext + zyzctext, 'example.text');
      // }
    },
    created() {
      this.tableData = this.myData;
      this.totalItems = this.tableData.length;
      this.paginateData();
    },
  };
  </script>
  <style>
  .upload-demo {
    display: inline-block;
    margin-right: 10px;
  }
  </style>
  